/**
 * 
 */
package note;

/**
 * @author Kevin Hanson
 *
 */

import javax.swing.*;

import database.Database;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class NotePanel extends JPanel {
	private Connection conn = null;
	private static Statement stat = null;
	private ResultSet rs = null;
	private DefaultListModel notebookListModel = null;
	private JList notebookList = null;
	private JTextArea textArea = null;

	public NotePanel() {
		try { // Initialize database
			conn = Database.getConnection();
			stat = conn.createStatement();
		} catch (SQLException ex) {
			System.err.print(ex.getMessage());
			ex.printStackTrace();
		}

		createGUI();

		updateNotebookListData();
		updateNoteContentData();
	}

	private void createGUI() {
		setLayout(new BorderLayout());

		// Notebook list, west pane
		notebookListModel = new DefaultListModel();
		notebookList = new JList(notebookListModel);
		notebookList.addMouseListener(new NotebookMouseListener());

		JScrollPane noteBookListScrollPane = new JScrollPane(notebookList);
		noteBookListScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		noteBookListScrollPane.setPreferredSize(new Dimension(120, 60));
		noteBookListScrollPane.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder("Notebook List"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));

		// Note content, center pane
		textArea = new JTextArea();
		textArea.setDoubleBuffered(true);
		textArea.setLineWrap(true);
		textArea.setFont(new Font(null, Font.BOLD, 16));
		JScrollPane areaScrollPane = new JScrollPane(textArea);
		areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		areaScrollPane.setPreferredSize(new Dimension(100, 60));
		areaScrollPane.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder("Plain text"), 
				BorderFactory.createEmptyBorder(5, 5, 5, 5)));

		// Action buttons, east pane
		JPanel p = new JPanel();
		p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
		p.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Action"),
				BorderFactory.createEmptyBorder(5, 5, 5, 5)));

		JButton jb0 = new JButton("Save");
		jb0.setMinimumSize(new Dimension(100, 20));
		jb0.setMaximumSize(new Dimension(100, 20));
		jb0.addActionListener(new NotebookButtonListener());
		JButton jb1 = new JButton("New");
		jb1.setMinimumSize(new Dimension(100, 20));
		jb1.setMaximumSize(new Dimension(100, 20));
		jb1.addActionListener(new NotebookButtonListener());
		JButton jb2 = new JButton("Delete");
		jb2.setMinimumSize(new Dimension(100, 20));
		jb2.setMaximumSize(new Dimension(100, 20));
		jb2.addActionListener(new NotebookButtonListener());

		p.add(jb0);
		p.add(jb1);
		p.add(jb2);

		add(noteBookListScrollPane, BorderLayout.WEST);
		add(areaScrollPane, BorderLayout.CENTER);
		add(p, BorderLayout.EAST);
	}

	private void updateNoteContentData() {
		if (notebookList.getSelectedIndex() == -1) // no selection
			notebookList.setSelectedIndex(0);
		String name = notebookListModel.getElementAt(notebookList.getSelectedIndex()).toString().replace("'--".subSequence(0, 1), "''--".subSequence(0, 2));;
		String str = String.format("SELECT content FROM notebook WHERE name = '%s';", name);
		try {
			rs = stat.executeQuery(str);
			str = rs.getString("content");
			str = (str == null) ? " " : str;
			textArea.setText(str);
			rs.close();
		} catch (SQLException ex) {
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void updateNotebookListData() {
		notebookListModel.removeAllElements();
		try {
			rs = stat.executeQuery("SELECT name FROM notebook ORDER BY date;");
			while (rs.next()) {
				notebookListModel.addElement(rs.getString("name"));
			}
			rs.close();
		} catch (SQLException ex) {
			System.out.print(ex.getMessage());
			ex.printStackTrace();
		}
	}

	class NotebookButtonListener implements ActionListener {
		public NotebookButtonListener() {
		}

		@Override
		public void actionPerformed(final ActionEvent e) {
			javax.swing.SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					try {
						if (e.getActionCommand() == "New") {
							stat.execute("INSERT INTO notebook VALUES (null, datetime('now'), 'New notebook', null);");
							if (!conn.getAutoCommit())
								conn.commit();

							updateNotebookListData();
							updateNoteContentData();
						} else if (e.getActionCommand() == "Delete") {
							String name = notebookListModel.getElementAt(notebookList.getSelectedIndex()).toString();
							String str = String.format("DELETE FROM notebook WHERE name = '%s';", name);
							stat.execute(str);
							// System.out.println(str);
							if (!conn.getAutoCommit())
								conn.commit();

							updateNotebookListData();
							updateNoteContentData();
						} else if (e.getActionCommand() == "Save") {
							// substitute ' with '' as SQL syntax required
							String name = notebookListModel.getElementAt(notebookList.getSelectedIndex()).toString().replace("'--".subSequence(0, 1), "''--".subSequence(0, 2));
							String context = textArea.getText().replace("'--".subSequence(0, 1), "''--".subSequence(0, 2));
							String newName = new String();
							if (context.length() > 8) {
								newName = context.substring(0, 8).replace("'--".subSequence(0, 1), "''--".subSequence(0, 2));
								context = context.substring(8);
							}
							String str = String.format("UPDATE notebook SET content = '%s', name = '%s' WHERE name = '%s';", context, newName, name);
//							System.out.println(context);
							stat.execute(str);
							if (!conn.getAutoCommit())
								conn.commit();
							updateNotebookListData();
							updateNoteContentData();
						}
					} catch (SQLException ex) {
						System.out.print(ex.getMessage());
						ex.printStackTrace();
					}
				}
			});
		}
	}

	public class NotebookMouseListener extends MouseAdapter {
		/*
		 * Invoke a thread to update diary content
		 * 
		 * @see
		 * java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
		 */
		@Override
		public void mouseClicked(MouseEvent e) {
			int button = e.getButton();
			if (button == MouseEvent.BUTTON1) {
				if (e.getClickCount() == 2 && !notebookList.isSelectionEmpty()) {
					javax.swing.SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							updateNoteContentData();
						}
					});
				}
			} else if (button == MouseEvent.BUTTON2) {
			} else if (button == MouseEvent.BUTTON3) {
			}
		}
		private JPopupMenu menu = null;

		public NotebookMouseListener() {
			menu = new JPopupMenu("Popup");
			JMenuItem item = new JMenuItem("Open");
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Menu item Open");
				}
			});
			menu.add(item);

			item = new JMenuItem("New");
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Menu item New");
				}
			});
			menu.add(item);

			item = new JMenuItem("Delete");
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Menu item Delete");
				}
			});
			menu.add(item);
		}

		public NotebookMouseListener(JPopupMenu m) {
			menu = m;
		}

		public void mousePressed(MouseEvent ev) {
			if (ev.isPopupTrigger()) {
				menu.show(ev.getComponent(), ev.getX(), ev.getY());
			}
		}

		public void mouseReleased(MouseEvent ev) {
			if (ev.isPopupTrigger()) {
				menu.show(ev.getComponent(), ev.getX(), ev.getY());
			}
		}
	}
}
